package support

import (
	"ia/common/support/global"
	"io"
	"log"
	"os"
	"time"

	"github.com/kataras/golog"
	"github.com/kataras/iris/v12/middleware/accesslog"
	"github.com/sirupsen/logrus"
)

const (
	// deleteFileOnExit = false
	//sysTimeform      = "2006/01/02 - 15:04:05"
	sysTimeform      = "2006-01-02 15:04:05"
	sysTimeformShort = "2006-01-02"
	dir              = "logs"
	reqLogDir        = dir + "/request/"
	otherLogDir      = dir + "/other/"
)

func InitLog() {
	var (
		err error
	)
	// if err = os.MkdirAll(reqLogDir, os.ModePerm); err != nil {
	// 	log.Fatal(err)
	// }
	if err = os.MkdirAll(otherLogDir, os.ModePerm); err != nil {
		log.Fatal(err)
	}
	initGolog()
}

func initGolog() {
	file := func(filename string) *os.File {
		var (
			file *os.File
			err  error
		)
		file, err = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			golog.Fatalf("初始化 golog 日志文件错误: %s\n", err.Error())
		}
		return file
	}(otherLogDir + "other_" + time.Now().Format(sysTimeformShort) + ".log")

	//logrus.SetLevel(logrus.InfoLevel)
	logrus.SetLevel(logrus.Level(global.GConfig.App.Own.LogrusLevel))
	logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: sysTimeform})
	logrus.SetOutput(io.MultiWriter(file, os.Stdout))

	golog.Install(logrus.StandardLogger())
}

func NewRequestLogger() *accesslog.AccessLog {
	ac := accesslog.File(reqLogDir + "access_" + time.Now().Format(sysTimeformShort) + ".log")
	defer ac.Close()
	ac.ResponseBody = false
	ac.LatencyRound = time.Second
	ac.TimeFormat = ""
	//ac.SetFormatter(&accesslog.CSV{Header: true,})
	ac.SetFormatter(&accesslog.JSON{Indent: "  ", HumanTime: true})
	return ac
}
